package com.example.rabbitmq.message;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Map;

/**
 * @author： ygl
 * @date： 2019/06/15
 * @Description：
 * 测试消息的属性
 */
public class MyConsumer {

    public static void main(String[] args) throws Exception {

        // 1.创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        // 2.通过链接工厂创建链接
        Connection connection = connectionFactory.newConnection();
        // 3.通过connection创建channel信道
        Channel channel = connection.createChannel();

        String queueName = "test001";
        channel.queueDeclare(queueName,true,false,false,null);

        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                String msg = new String(body,"utf-8");
                System.out.println("默认的消费者消费消息-----："+msg);
                Map<String, Object> headers = properties.getHeaders();
                for (Map.Entry<String, Object> entry : headers.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    System.out.println("消息的headers值--:"+key+":"+value);
                }
            }
        };
        channel.basicConsume(queueName, true, defaultConsumer);
    }
}
